<template>
	<div>
		<xn-form-container
			:title="formData.id ? '编辑' : '新增'"
			:width="1000"
			:visible="visible"
			:destroy-on-close="true"
			@close="onClose"
		>
			<a-form
				:wrapper-col="{ span: 16 }"
				:label-col="{ span: 8 }"
				autocomplete="off"
				labelAlign="right"
				ref="formRef"
				:model="formData"
				:rules="formRules"
			>
				<a-row>
					<a-col :span="12">
						<a-form-item label="交货单位" name="deliveryUnitId">
							<a-tree-select
								v-model:value="formData.deliveryUnitId"
								style="width: 100%"
								:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
								placeholder="请选择交货单位"
								allow-clear
								tree-default-expand-all
								:tree-data="treeData"
								:field-names="{
									children: 'children',
									label: 'name',
									value: 'id'
								}"
								selectable="false"
								tree-line
							></a-tree-select>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="交货日期" name="deliveryDate">
							<a-date-picker :getCalendarContainer="trigger => trigger.parentNode" format="YYYY-MM-DD" style="width: 100%" v-model:value="formData.deliveryDate" />
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="12">
						<a-form-item label="验收人" name="acceptPerName">
							<div @click="selectionParticipants('acceptPerId')">
								<a-input readonly v-model:value="formData.acceptPerName" placeholder="请选择验收人" allow-clear />
							</div>
						</a-form-item>
					</a-col>
					<a-col :span="12">
						<a-form-item label="保管人" name="custodianName">
							<div @click="selectionParticipants('custodianId')">
								<a-input readonly v-model:value="formData.custodianName" placeholder="请选择保管人" allow-clear />
							</div>
						</a-form-item>
					</a-col>
				</a-row>
				<a-row>
					<a-col :span="12">
						<a-form-item label="收货仓库" name="warehouseId">
							<xn-page-selector
								@change="onWarehouseChange"
								ref="warehouseRef"
								:field-names="{ label: 'warehouseName', value: 'id' }"
								:page-function="(param) => storeCenterApi.getPage(param)"
								v-model:value="formData.warehouseId"
								placeholder="请选择仓库"
							>
							</xn-page-selector>
						</a-form-item>
					</a-col>
				</a-row>

				<a-row>
					<a-col :span="24">
						<a-row>
							<a-button type="primary" class="childAddButton" @click="addProduct()">
								<PlusOutlined />
								新增
							</a-button>
							<a-popconfirm title="是否删除?" @confirm="removeGoods()">
								<a-button style="margin-left: 12px" type="remove" danger>
									<LineOutlined />
									删除
								</a-button>
							</a-popconfirm>
						</a-row>
						<a-table
							:row-selection="options.rowSelection"
							:pagination="false"
							:columns="goodsColumns"
							:data-source="formData.productStorageDetailAddParamList"
							:scroll="{ x: 1000 }"
						>
							<template #bodyCell="{ index, record, column }">
								<template v-if="column.dataIndex === 'index'">
									<span>{{ index + 1 }}</span>
								</template>
								<template v-if="column.dataIndex === 'productNo'">
									<a-input :style="{ width: column.width }" v-model:value="record.productNo" />
								</template>
								<template v-if="column.dataIndex === 'product'">
									<a-input :style="{ width: column.width }" v-model:value="record.product" />
								</template>
								<template v-if="column.dataIndex === 'unit'">
									<a-input :style="{ width: column.width }" v-model:value="record.unit" />
								</template>
								<template v-if="column.dataIndex === 'spec'">
									<a-input :style="{ width: column.width }" v-model:value="record.spec" />
								</template>
								<template v-if="column.dataIndex === 'price'">
									<a-input @input="priceChange(record)" :style="{ width: column.width }" v-model:value="record.price" />
								</template>
								<template v-if="column.dataIndex === 'taxRate'">
									<a-input
										@input="taxRateChange(record)"
										:style="{ width: column.width }"
										v-model:value="record.taxRate"
									/>
								</template>

								<template v-if="column.dataIndex === 'num'">
									<a-input
										@input="orderNumChange(record)"
										:style="{ width: column.width }"
										v-model:value="record.num"
									/>
								</template>

								<template v-if="column.dataIndex === 'taxPrice'">
									<a-input
										@input="taxChange(record)"
										:style="{ width: column.width }"
										v-model:value="record.taxPrice"
									/>
								</template>

								<template v-if="column.dataIndex === 'noTaxPrice'">
									<a-input
										@input="excludingTaxChange(record)"
										:style="{ width: column.width }"
										v-model:value="record.noTaxPrice"
									/>
								</template>

								<template v-if="column.dataIndex === 'remark'">
									<a-input :style="{ width: column.width }" v-model:value="record.remark" />
								</template>
							</template>
						</a-table>
					</a-col>
				</a-row>
				<div style="margin-top: 15px">
					<span style="color: #333; font-size: 16px; font-weight: 600">合计</span>
				</div>
				<a-row :gutter="24" style="margin-bottom: 50px; margin-top: 15px; margin-left: 20px">
					<a-col :span="6">
						<div style="margin-right: 12px; display: inline-block">
							<span>入库数量:</span>
						</div>
						<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="totalNum" />
					</a-col>
					<a-col :span="6">
						<div style="margin-right: 12px; display: inline-block">
							<span>含税总金额</span>
						</div>
						<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="taxAmount" />
					</a-col>
					<a-col :span="6">
						<div style="margin-right: 12px; display: inline-block">
							<span>不含税总金额</span>
						</div>
						<a-input style="width: 50%; border-radius: 5px" disabled placeholder="0" v-model:value="noTaxAmount" />
					</a-col>
				</a-row>
			</a-form>

			<template #footer>
				<a-button type="primary" @click="onSubmit" :loading="submitLoading">提交</a-button>
			</template>
		</xn-form-container>

		<user-selector-plus
			ref="userSelectorPlusRef"
			:org-tree-api="selectorApiFunction.orgTreeApi"
			:user-page-api="selectorApiFunction.userPageApi"
			:checked-user-list-api="selectorApiFunction.checkedUserListApi"
			:data-is-converter-flw="true"
			@onBack="selectUserCallback"
		/>
	</div>
</template>

<script setup name="produceStorgeForm">
	import { required } from '@/utils/formRules'
	import storeCenterApi from '@/api/base_data/storeCenterApi'
	import { message } from 'ant-design-vue'
	import { toRaw } from 'vue'
	import bizPositionApi from '@/api/biz/bizPositionApi'
	import UserSelectorPlus from '@/components/Selector/userSelectorPlus.vue'
	import dayjs from 'dayjs'
	import productstorageApi from '@/api/produce/productstorageApi'
	import orgApi from '@/api/sys/orgApi'
	import userCenterApi from '@/api/sys/userCenterApi'
	import xnPageSelector from '@/components/XnPageSelect/index.vue'
	import tool from '@/utils/tool'
	// 定义emit事件
	//PROCUREMENT_PARTNERS
	const emit = defineEmits({ successful: null })
	// 默认是关闭状态
	const visible = ref(false)
	const formRef = ref()
	const warehouseRef = ref()
	let userType = 'acceptPerId'
	// 表单数据，也就是默认给一些数据
	const formData = ref({})
	const submitLoading = ref(false)
	const totalNum = ref(0)
	const taxAmount = ref(0)
	const noTaxAmount = ref(0)
	const userSelectorPlusRef = ref()
	const selectorApiFunction = {
		orgTreeApi: (param) => {
			return orgApi.orgOrgTreeSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		userPageApi: (param) => {
			return orgApi.orgUserSelector(param).then((data) => {
				return Promise.resolve(data)
			})
		},
		checkedUserListApi: (param) => {
			return userCenterApi.userCenterGetUserListByIdList(param).then((data) => {
				return Promise.resolve(data)
			})
		}
	}

	const selectionParticipants = (type) => {
		userType = type
		let data = []
		if (type == 'acceptPerId') {
			if (formData.value.acceptPerId) {
				data.push({
					key: 'USER',
					label: formData.value.acceptPerName,
					value: formData.value.acceptPerId
				})
			}
		} else if (formData.value.custodianId) {
			data.push({
				key: 'USER',
				label: formData.value.custodianName,
				value: formData.value.custodianId
			})
		}
		userSelectorPlusRef.value.showUserPlusModal(data)
	}

	const selectUserCallback = (value) => {
		if (userType == 'acceptPerId') {
			formData.value.acceptPerId = value.value
			formData.value.acceptPerName = value.label
		} else {
			formData.value.custodianId = value.value
			formData.value.custodianName = value.label
		}
	}

	// 定义机构元素
	const treeData = ref([])

	// 打开抽屉
	const onOpen = (record) => {
		visible.value = true
		formData.value = {}
		if (record) {
			let params = { ...record }
			params.deliveryDate = ref(dayjs(params.deliveryDate))
			totalNum.value = params.totalNum
			noTaxAmount.value = params.noTaxPrice
			taxAmount.value = params.taxPrice
			formData.value = params
			loadDetail(params)
		} else {
			formData.value.deliveryDate = ref(dayjs())
		}
		bizPositionApi.positionOrgTreeSelector().then((res) => {
			treeData.value = res
		})
		nextTick(() => {
			warehouseRef.value.onPage({})
		})
	}

	const loadDetail = (record) => {
		productstorageApi
			.detail({
				id: record.id
			})
			.then((res) => {
				res.productStorageDetailList.forEach((element) => {
					element['key'] = element['materialId']
				})
				formData.value.productStorageDetailAddParamList = res.productStorageDetailList
			})
			.catch(() => {})
	}

	const options = {
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}

	const removeGoods = () => {
		let datas = formData.value.productStorageDetailAddParamList
		selectedRowKeys.value.forEach((element) => {
			let index = datas.findIndex((it) => {
				return it['key'] == element
			})
			if (index >= 0) {
				datas.splice(index, 1)
			}
		})

		selectedRowKeys.value = []
		totalNum.value = totalOrderNum()
		taxAmount.value = totalTax()
		noTaxAmount.value = totalExcludingTaxTax()
	}
	const selectedRowKeys = ref([])

	const formatPrice = (text) => {
		let value = text.match(/^\d*(\.?\d{0,2})/g)[0] || null
		if (isNaN(value)) {
			return ''
		}
		return value
	}
	const priceChange = (record) => {
		record.price = formatPrice(record.price)
	}

	const taxChange = (record) => {
		record.taxPrice = formatPrice(record.taxPrice)
		taxAmount.value = totalTax()
	}

	const excludingTaxChange = (record) => {
		record.noTaxPrice = formatPrice(record.noTaxPrice)
		noTaxAmount.value = totalExcludingTaxTax()
	}

	const orderNumChange = (record) => {
		let value = record.num.replace(/[^\d]+/g, '')
		if (isNaN(value)) {
			record.num = ''
		} else {
			record.num = value
		}
		totalNum.value = totalOrderNum()
	}

	const taxRateChange = (record) => {
		let value = record.taxRate.replace(/[^\d]+/g, '')
		if (isNaN(value)) {
			record.taxRate = ''
		} else {
			record.taxRate = value
		}
	}
	const totalExcludingTaxTax = () => {
		let orderList = formData.value.productStorageDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let noTaxPrice = it['noTaxPrice']
			if (noTaxPrice) {
				amount += parseFloat(noTaxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}
	const totalTax = () => {
		let orderList = formData.value.productStorageDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let taxPrice = it['taxPrice']
			if (taxPrice) {
				amount += parseFloat(taxPrice)
			}
		})
		return amount.toFixed(2).replace('.00', '')
	}

	const totalOrderNum = () => {
		let orderList = formData.value.productStorageDetailAddParamList || []
		let amount = 0
		orderList.forEach((it) => {
			let orderNum = it['num']
			if (orderNum) {
				amount += parseInt(orderNum)
			}
		})
		return amount
	}

	// 关闭抽屉
	const onClose = () => {
		visible.value = false
	}

	// 默认要校验的
	const formRules = {
		warehouseId: [required('请选择仓库')],
		deliveryUnitId: [required('请选择交货单位')],
		deliveryDate: [required('请选择交货日期')],
		acceptPerName: [required('请选择验收人')],
		custodianName: [required('请选择保管人')]
	}
	const addProduct = () => {
		if (!formData.value.productStorageDetailAddParamList) {
			formData.value.productStorageDetailAddParamList = []
		}
		formData.value.productStorageDetailAddParamList.push({
			key: tool.snowyUuid()
		})
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				let orderList = toRaw(formData.value.productStorageDetailAddParamList) || []
				if (orderList.length <= 0) {
					message.error('请添加产品')
					return
				}
				let msg = null
				let itemRules = [
					{
						field: 'productNo',
						error: '产品编号不能为空!'
					},
					{
						field: 'product',
						error: '产品名称不能为空!'
					},
					{
						field: 'price',
						error: '入库价格不能为空!'
					},
					{
						field: 'num',
						error: '入库数量不能为空!'
					}
				]
				for (let i = 0; i < orderList.length; i++) {
					for (let rule of itemRules) {
						let item = orderList[i]
						let itemValue = item[rule['field']]
						if (!itemValue) {
							msg = `第${i + 1}行${rule['error']}`
							break
						}
					}
				}
				if (msg) {
					message.error(msg)
					return
				}
				submitLoading.value = true
				let params = { ...formData.value }
				let detailAddParamList = params.productStorageDetailAddParamList
				let formatreDeliveryDate = params.deliveryDate.format('YYYY-MM-DD HH:mm:ss')
				if (params.id) {
					params.productStorageDetailEditParamList = detailAddParamList
					params.productStorageDetailAddParamList = undefined
				} else {
					params.productStorageDetailAddParamList = detailAddParamList
				}
				productstorageApi
					.addOrEdit(
						Object.assign(params, {
							deliveryDate: formatreDeliveryDate,
							noTaxPrice: noTaxAmount.value,
							taxPrice: taxAmount.value,
							totalNum: totalNum.value
						})
					)
					.then(() => {
						visible.value = false
						emit('successful')
					})
					.catch(() => {})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {})
	}
	// 调用这个函数将子组件的一些数据和方法暴露出去
	defineExpose({
		onOpen
	})

	const goodsColumns = [
		{
			title: '序号',
			width: 80,
			dataIndex: 'index',
			align: 'center'
		},
		{
			title: '产品编号',
			width: 120,
			dataIndex: 'productNo',
			align: 'center',
			ellipsis: true
		},
		{
			title: '产品名称',
			dataIndex: 'product',
			width: 180,
			align: 'center',
			ellipsis: true
		},

		{
			title: '入库价格',
			dataIndex: 'price',
			width: 120,
			align: 'center'
		},

		{
			title: '单位',
			dataIndex: 'unit',
			width: 120,
			align: 'center'
		},
		{
			title: '规格',
			dataIndex: 'spec',
			width: 120,
			align: 'center'
		},
		{
			title: '税率',
			dataIndex: 'taxRate',
			width: 120,
			align: 'center'
		},
		{
			title: '入库数量',
			dataIndex: 'num',
			width: 120,
			align: 'center'
		},
		{
			title: '含税金额',
			dataIndex: 'taxPrice',
			width: 120,
			align: 'center'
		},
		{
			title: '不含税金额',
			dataIndex: 'noTaxPrice',
			width: 140,
			align: 'center'
		},
		{
			title: '备注',
			dataIndex: 'remark',
			width: 200,
			align: 'center'
		}
	]
</script>

<style scoped :type="less">
	.childAddButton {
		margin-bottom: 10px;
	}
</style>
